package com.orangelife.mobile.goodsrent.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.util.OrangePhoneUtil;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.CountDownHandler;
import com.curry.android.util.DialogHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.goodsrent.adapter.GoodsRentOrderDetailListAdapter;
import com.orangelife.mobile.goodsrent.adapter.GoodsRentStatesListAdapter;
import com.orangelife.mobile.goodsrent.biz.GoodsRentBiz;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.widget.ScrollListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created by yyx
 * on 2015/12/16.
 * 租借订单详情
 */
public class GoodsRentOrderDetailActivity extends OrangeLifeBaseActivity implements View.OnClickListener {

    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tvRight)
    TextView tvRight;
    @Bind(R.id.iv_title_right)
    ImageView ivTitleRight;
    @Bind(R.id.llRightClick)
    LinearLayout llRightClick;
    @Bind(R.id.iv_username)
    ImageView ivUsername;
    @Bind(R.id.tv_username)
    TextView tvUsername;
    @Bind(R.id.tv_userphone)
    TextView tvUserphone;
    @Bind(R.id.iv_phone)
    ImageView ivPhone;
    @Bind(R.id.rlUser)
    RelativeLayout rlUser;
    @Bind(R.id.v_separated)
    View vSeparated;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tvOrderNumber)
    TextView tvOrderNumber;
    @Bind(R.id.tvOrderStatus)
    TextView tvOrderStatus;
    @Bind(R.id.tvOrderHaveTime)
    TextView tvOrderHaveTime;
    @Bind(R.id.tvPlaceOrderTime)
    TextView tvPlaceOrderTime;
    @Bind(R.id.tvOrderMoney)
    TextView tvOrderMoney;
    @Bind(R.id.slGoods)
    ScrollListView slGoods;
    @Bind(R.id.btnJudge)
    Button btnJudge;
    @Bind(R.id.tvServiceOrder)
    TextView tvServiceOrder;
    @Bind(R.id.slGoodsRentStates)
    ScrollListView slGoodsRentStates;
    @Bind(R.id.llOrderHaveTime)
    LinearLayout llOrderHaveTime;
    @Bind(R.id.viewOrderHaveTime)
    View viewOrderHaveTime;
    /**
     * 商品列表
     */
    private GoodsRentOrderDetailListAdapter goodsAdapter;
    /**
     * 状态时间轴
     */
    private GoodsRentStatesListAdapter statesAdapter;
    /**
     * 商品列表数据
     */
    private List<Map<String, Object>> goodsList;
    /**
     * 状态列表数据
     */
    private List<Map<String, Object>> stateslist;
    /**
     * 请求地址
     */
    private String url = "";
    /**
     * 接取服务端数据
     */
    private Map<String, Object> mapDetail;

    private String orderID = "";

    private long longTime;

    Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodsrent_order_detail);
        ButterKnife.bind(this);
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getDetail();
    }

    /**
     * 初始化赋值
     */
    private void findView() {
        tvTitle.setText("订单详情");
        Intent intent = getIntent();
        orderID = intent.getStringExtra("orderID");
        ivTitleRight.setVisibility(View.VISIBLE);
        ivTitleRight.setBackgroundResource(R.drawable.icon_phone);
        btnJudge.setOnClickListener(this);
        ivTitleRight.setOnClickListener(this);
        getDataFromServer();
        getDetail();
        setAdapter();
    }

    /***
     * 设置adapter
     */
    private void setAdapter() {
        goodsList = new ArrayList<>();
        stateslist = new ArrayList<>();
        goodsAdapter = new GoodsRentOrderDetailListAdapter(this, goodsList);
        statesAdapter = new GoodsRentStatesListAdapter(this, stateslist);
        slGoods.setAdapter(goodsAdapter);
        slGoodsRentStates.setAdapter(statesAdapter);
    }

    /**
     * 获取详情
     */
    private void getDetail() {
        url = Constant.URL_GOODRENT_ORDER_DETAIL;
        HashMap<String, String> map = new HashMap<>();
        map.put("{orderID}", orderID);
        GoodsRentBiz.getInstance().requestGet(map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                DialogHelper.closeDialog(dialog);
                if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                    mapDetail = GoodsRentBiz.getInstance().handleOrderDetail(response, errCode);
                    setDetail();
                }
            }
        }, url);
    }

    /**
     * 设置状态
     */
    private void setPut() {
        url = Constant.URL_GOODRENT_ORDER_EDIT;
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderID", orderID);
        map.put("orderStatus","2");
        map.put("payStatus","0");
        map.put("remark","");
        GoodsRentBiz.getInstance().requesPut(map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                DialogHelper.closeDialog(dialog);
            }
        }, url);
    }

    /***
     * 详情设置
     */
    private void setDetail() {
        //分别获取到goodslist的数据和stateslist的数据  发货的那个view的长度是86dp
        stateslist.clear();
        goodsList = (List<Map<String, Object>>) mapDetail.get("orderDetails");
        List<Map<String,Object>> listS = (List<Map<String, Object>>) mapDetail.get("orderHistory");
        for (int i = 0; i < listS.size(); i++) {
            stateslist.add(listS.get(listS.size() - 1 - i));
        }
        goodsAdapter.setList(goodsList);
        goodsAdapter.notifyDataSetChanged();
        String orderStatus = mapDetail.get("orderStatus").toString();
        String orderStatusStr = "";
//        left = DateUtil.getInstance().haveTime_(mapDetail.get("tscreate").toString(),mapDetail.get("time").toString());
        String time = mapDetail.get("time").toString();
        /*if (!StringUtil.isBlank(time)){
            longTime = Long.parseLong(time);
        }*/
        switch (orderStatus) {
            case "1":
                orderStatusStr = "待付款";
                startTimer(time);
                break;
            case "2":
                orderStatusStr = "已超时";
                tvOrderHaveTime.setText("订单已超时不能支付");
                stateslist.clear();
                break;
            case "3":
                orderStatusStr = "待发货";
                tvOrderHaveTime.setText(orderStatusStr);
                llOrderHaveTime.setVisibility(View.GONE);
                viewOrderHaveTime.setVisibility(View.GONE);
                break;
            case "4":
                orderStatusStr = "已发货";
                tvOrderHaveTime.setText(orderStatusStr);
                llOrderHaveTime.setVisibility(View.GONE);
                viewOrderHaveTime.setVisibility(View.GONE);
                break;
            case "5":
                orderStatusStr = "已逾期";
                tvOrderHaveTime.setText(orderStatusStr);
                llOrderHaveTime.setVisibility(View.GONE);
                viewOrderHaveTime.setVisibility(View.GONE);
                break;
            case "6":
                orderStatusStr = "已归还";
                tvOrderHaveTime.setText(orderStatusStr);
                btnJudge.setVisibility(View.VISIBLE);
                btnJudge.setText("去评价");
                llOrderHaveTime.setVisibility(View.GONE);
                viewOrderHaveTime.setVisibility(View.GONE);
                break;
            case "7":
                orderStatusStr = "已丢失";
                tvOrderHaveTime.setText(orderStatusStr);
                llOrderHaveTime.setVisibility(View.GONE);
                viewOrderHaveTime.setVisibility(View.GONE);
                break;
            case "8":
                orderStatusStr = "已评价";
                tvOrderHaveTime.setText(orderStatusStr);
                btnJudge.setVisibility(View.VISIBLE);
                btnJudge.setText("查看评价");
                llOrderHaveTime.setVisibility(View.GONE);
                viewOrderHaveTime.setVisibility(View.GONE);
                break;

            default:
                break;
        }
        tvServiceOrder.setText(mapDetail.get("companyName").toString()+"物业 "+mapDetail.get("comm").toString());
        statesAdapter.setList(stateslist);
        statesAdapter.notifyDataSetChanged();
        tvUsername.setText(mapDetail.get("shipName").toString());
        tvUserphone.setText(mapDetail.get("shipPhone").toString());
        tvAddress.setText(mapDetail.get("shipAddr").toString());
        tvOrderNumber.setText(mapDetail.get("orderID").toString());
        tvOrderStatus.setText(orderStatusStr);
        tvPlaceOrderTime.setText(DateUtil.getInstance().tranStringForDate(mapDetail.get("tscreate").toString()));
        tvOrderMoney.setText("¥"+mapDetail.get("totalCost").toString());



    }



    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    private void startTimer(String second){
        CountDownHandler handler = new CountDownHandler(tvOrderHaveTime,0);
        handler.setOnCountDownTimerFinishedListener(new CountDownHandler.OnCountDownTimerFinishedListener() {
            @Override
            public void onFinish() {
                tvOrderHaveTime.setText("订单已超时不能支付");
                tvOrderStatus.setText("已超时");
                setPut();
            }

            @Override
            public void onCountDown(String currentSecond) {

            }
        });
        handler.startTimer(second);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnJudge:
                String btnJudgeStr = btnJudge.getText().toString();
                Intent intent = new Intent();
                intent.setClass(GoodsRentOrderDetailActivity.this, GoodsRentAddJudgementActivity.class);
                intent.putExtra("orderID", mapDetail.get("orderID").toString());
                intent.putExtra("scorerID", mapDetail.get("merID").toString());
                if ("去评价".equals(btnJudgeStr)) {
                    intent.putExtra("status", "3");

                } else {
                    intent.putExtra("status", "4");
                }
                startActivity(intent);
                break;
            case R.id.iv_title_right:
                OrangePhoneUtil.callCommProperty(GoodsRentOrderDetailActivity.this);
                break;
            default:
                break;
        }
    }


}
